<template>
  <el-card shadow="never">
    <el-form :model="form" ref="form" :rules="rules" label-width="100px">
      <el-row :gutter="16">
        <el-col>
          <el-form-item label="通知类型：" prop="publicTag">
            <el-radio-group size="small" v-model="form.publicTag">
              <el-radio-button :label="0">系统通知</el-radio-button>
              <el-radio-button :label="1">系统公告</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="form.publicTag === 0">
          <el-form-item label="通知分类：" prop="notifyTypeId">
            <el-select clearable v-model="form.notifyTypeId">
              <el-option
                v-for="(item,index) in typeList"
                :key="index"
                :label="item.notifyType"
                :value="item.notifyTypeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发送对象：" prop="mesType" v-if="form.publicTag === 0">
            <el-radio-group size="small" @change="handleTypeChange" v-model="form.mesType">
              <el-radio-button :label="1">部门</el-radio-button>
              <el-radio-button :label="2">岗位</el-radio-button>
              <el-radio-button :label="3">人员</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item class="select-form" label="接收人：" v-show="form.publicTag === 0">
            <el-select
              clearable
              v-show="!form.mesType"
              style="width: 100%"
              v-model="form.recipient"
            />
            <dept-select
              v-show="form.mesType === 1"
              ref="deptSelect"
              multiple
              :selectValue="form.recipientId"
              @select="e => handleDeptSelect(e, 'dept')"
              @cancelSelect="e => handleCancelSelect(e, 'dept')"
            />
            <dept-position-s
              v-show="form.mesType === 2"
              ref="deptSelectS"
              :selectValue="form.recipientId"
              multiple
              @select="e => handleDeptSelect(e, 'position')"
              @cancelSelect="e => handleCancelSelect(e, 'position')"
            />
            <div v-show="form.mesType === 3">
              <dept-user-s
                ref="deptUserS"
                @cancelSelect="e => handleCancelSelect(e, 'user')"
                @select="handleUserSelect"
                :multiple="true"
              />
              <!-- <el-tag
                :key="tag"
                v-for="tag in userSelect"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >{{tag.userName}}</el-tag>
              <el-button
                type="primary"
                class="button-new-tag ml10"
                @click="$refs.deptPositionMan.show()"
                size="small"
              >+ 添加人员</el-button>-->
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="mb0" label="发送方式：" prop="scheduleTag">
            <el-radio-group size="small" @change="handleRadioChange" v-model="form.scheduleTag">
              <el-radio-button :label="0">立即</el-radio-button>
              <el-radio-button :label="1">定时</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="mb0" label="发送短信：" prop="smsFlag">
            <el-radio-group size="small" v-model="form.smsFlag">
              <el-radio-button :label="0">是</el-radio-button>
              <el-radio-button :label="1">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="mb0" label="发送时间：" v-show="form.scheduleTag === 1">
            <el-date-picker
              type="datetime"
              value-format="timestamp"
              v-model="form.sendTime"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider />
      <el-row :gutter="16">
        <el-col>
          <el-form-item label="标题：" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件：">
            <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              :file-list="fileList"
              class="file-upload"
              :on-remove="handleRemove"
              :http-request="customRequest"
            >
              <span>添加附件</span>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="内容：" prop="content">
            <el-input
              @blur="handleAreaBlur"
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="form.content"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="概述：" prop="description">
            <el-input
              :readOnly="getDescription"
              style="width: 90%"
              class="fl mr20"
              v-model="form.description"
              placeholder="请输入标题"
            />
            <el-checkbox v-model="getDescription" class="fl">自动读取</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col class="tl-center">
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
        </el-col>
      </el-row>
    </el-form>
    <dept-position-man :multiple="true" @handleSelected="handleUserSelect" ref="deptPositionMan" />
  </el-card>
</template>

<script>
import { saveOnlyUploads } from '@/api/supplier'
import { typeAll, notifyCreate, updateRead } from '@/api/notify'
import { openNotification } from '@/utils/util'
import DeptSelect from '@/components/DeptSelect'
import DeptPositionS from '@/components/DeptPositionS'
import DeptUserS from '@/components/DeptUserS'
import DeptPositionMan from '@/components/DeptPositionMan'

export default {
  components: {
    DeptSelect,
    DeptPositionS,
    DeptUserS,
    DeptPositionMan
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      form: {
        recipient: null,
        recipientId: null
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        publicTag: [{ required: true, message: '请选择通知类型', trigger: ['blur', 'change'] }],
        mesType: [{ required: true, message: '请选择发送对象', trigger: ['blur', 'change'] }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      getDescription: true,
      typeList: [],
      fileList: [], // 文件列表
      deptSelect: [],
      positionSelect: [],
      userSelect: [],
      loading: false
    }
  },
  mounted() {
    typeAll().then(res => {
      console.log('res', res)
      this.typeList = res.data
    })
  },
  methods: {
    // 发送对象 change
    handleTypeChange(e) {
      this.$refs.deptUserS.reset()
      this.$refs.deptSelectS.reset()
      this.$refs.deptSelect.reset()
    },
    // 发送方式 change
    handleRadioChange(e) {
      if (!e) {
        this.$set(this.form, 'sendTime', null)
      }
    },
    // tag删除方法
    handleClose(tag) {
      const index = this.userSelect.findIndex(v => v.userId === tag.userId)
      this.userSelect.splice(index, 1)
    },
    handleSubmit() {
      this.loading = false
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 上传附件处理
          let uploadArr = []
          if (this.fileList.length > 0) {
            this.fileList.map(v => {
              uploadArr.push({
                uploadId: v.uploadId
              })
            })
            this.$set(this.form, 'notifyAttachmentList', uploadArr)
          } else {
            uploadArr = [...this.fileList]
          }

          // 接收人处理
          let arr = []
          if (this.form.mesType === 1) {
            console.log('deptSelect', this.deptSelect)
            this.deptSelect.map(v => {
              arr.push(v.key)
            })
          } else if (this.form.mesType === 2) {
            this.positionSelect.map(v => {
              arr.push(v.key)
            })
          } else {
            this.userSelect.map(v => {
              let userId = v.key.split('-')[1]
              arr.push(userId)
            })
          }
          delete this.form.recipient
          this.$set(this.form, 'recipientId', arr.join(','))
          const res = await notifyCreate(this.form)
          if (res.state === '000000') {
            openNotification('success', '发送通知成功')
            this.$nextTick(() => {
              this.$refs.form.resetFields()
              this.fileList = []
              this.userSelect = []
              this.deptSelect = []
              this.positionSelect = []
              this.loading = false
            })
          }
        } else {
          this.loading = false
        }
      })
    },
    // 部门多选
    handleDeptSelect(value, str) {
      if (str === 'dept') {
        this.deptSelect.push(value)
      } else {
        this.positionSelect.push(value)
      }
    },
    // 取消选择
    handleCancelSelect(value, str) {
      if (str === 'dept') {
        const index = this.deptSelect.findIndex(v => v.key === value.key)
        this.deptSelect.splice(index, 1)
      } else if (str === 'position') {
        const index = this.positionSelect.findIndex(v => v.key === value.key)
        this.positionSelect.splice(index, 1)
      } else {
        const index = this.userSelect.findIndex(v => v.key === value.key)
        this.userSelect.splice(index, 1)
        console.log('userSelect', this.userSelect)
      }
    },
    handleUserSelect(value) {
      console.log('user select', value)
      let obj = Object.assign({}, value)
      this.userSelect.push(obj)
    },
    handleAreaBlur() {
      if (this.getDescription) {
        if (this.form.content) {
          const str = this.form.content.substring(0, 100)
          this.$set(this.form, 'description', str)
        }
      }
    },
    handleRemove(info) {
      const index = this.fileList.findIndex(v => v.uploadId === info.uploadId)
      this.fileList.splice(index, 1)
    },
    // 覆盖原本的上传方法
    customRequest(info, local) {
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          console.log('data', data)
          this.fileList.push(data)
          this.fileList[this.fileList.length - 1].status = 'done'
          this.fileList[this.fileList.length - 1].uploadId = data.uploadId
          this.fileList[this.fileList.length - 1].savePath = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].name = info.file.name

          console.log('fileList', this.fileList)
        }
      })
    }
  }
}
</script>

<style scoped>
.file-upload >>> .el-upload {
  width: auto;
  height: auto;
  line-height: inherit;
  border: none;
}

/* .select-form >>> .el-form-item__content,
.select-form >>> .el-form-item__label {
  line-height: 24px;
} */
</style>
